
package com.seeyon.apps.thirdapp.controller;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.thirdapp.constants.Constants;
import com.seeyon.apps.thirdapp.domain.AccessToken;
import com.seeyon.apps.thirdapp.util.LanxinUtil;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.authenticate.domain.UserHelper;
import com.seeyon.ctp.common.authenticate.sso.SSOTicketManager;
import com.seeyon.ctp.common.controller.BaseController;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.flag.BrowserEnum;
import com.seeyon.ctp.common.i18n.LocaleContext;
import com.seeyon.ctp.common.i18n.ResourceUtil;
import com.seeyon.ctp.common.init.MclclzUtil;
import com.seeyon.ctp.common.service.NeedlessCheckLoginAnnotationAware;
import com.seeyon.ctp.common.taglibs.functions.Functions;
import com.seeyon.ctp.common.web.filter.CTPCsrfGuard;
import com.seeyon.ctp.login.online.OnlineManager;
import com.seeyon.ctp.login.online.OnlineRecorder;
import com.seeyon.ctp.login.online.OnlineUser;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.organization.manager.OrgManagerDirect;
import com.seeyon.ctp.portal.sso.SSOTicketBean;
import com.seeyon.ctp.privilege.manager.PrivilegeMenuManager;
import com.seeyon.ctp.util.Base64;
import com.seeyon.ctp.util.*;
import com.seeyon.ctp.util.annotation.NeedlessCheckLogin;
import com.seeyon.ctp.util.json.JSONUtil;
import com.seeyon.v3x.common.web.login.CurrentUser;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

import static com.seeyon.ctp.common.GlobalNames.SESSION_CONTEXT_USERINFO_KEY;
import static com.seeyon.ctp.common.constants.Constants.SESSION_CURRENT_USER;

public class ThirdAppController  extends BaseController {
    private static final Log log = LogFactory.getLog(ThirdAppController.class);
    //   private OrgManagerDirect orgManagerDirect;

    private static final Class<?> c1 = MclclzUtil.ioiekc("com.seeyon.ctp.permission.bo.LicensePerInfo");
    private static Object isExceedMaxLoginNumberLock = new Object();
    private static Object o = null;
    private static int serverType;
    private OrgManager orgManager;
    private OnlineManager onlineManager;
    private OrgManagerDirect orgManagerDirect;
    private PrivilegeMenuManager privilegeMenuManager;

    /**
     * 并发数据初始化
     */
    private static void init() {
        if (o != null) {
            return;
        }
        o = MclclzUtil.invoke(c1, "getInstance", new Class[]{String.class}, null, new Object[]{""});
        serverType = (Integer) MclclzUtil.invoke(c1, "getserverType", null, o, null);
    }

    public void setOrgManager(OrgManager orgManager) {
        this.orgManager = orgManager;
    }

    public void setOnlineManager(OnlineManager onlineManager) {
        this.onlineManager = onlineManager;
    }

    public void setOrgManagerDirect(OrgManagerDirect orgManagerDirect) {
        this.orgManagerDirect = orgManagerDirect;
    }

    public void setPrivilegeMenuManager(PrivilegeMenuManager privilegeMenuManager) {
        this.privilegeMenuManager = privilegeMenuManager;
    }

//    public OrgManagerDirect getOrgManagerDirect() {
//        if(orgManagerDirect==null){
//            orgManagerDirect = (OrgManagerDirect) AppContext.getBean("orgManagerDirect");
//        }
//        return orgManagerDirect;
//    }
    @PostConstruct
    public void noAuthenticationInit() throws BusinessException {
        logger.info("初始化 ThirdAppController 免认证方法 --- 开始");
        NeedlessCheckLoginAnnotationAware needless = (NeedlessCheckLoginAnnotationAware) AppContext.getBean("NeedlessCheckLoginAnnotationAware");
        if (null != needless) {
            Set<String> m = new HashSet<String>();
            m.add("access");
            m.add("message");
            m.add("getErrorPage");
            m.add("ssoLogin");
            m.add("distribution");
            needless.getNeedlessUrlMap().put("/thirdApp.do", m);
            logger.info("初始化 ThirdAppController 免认证方法 --- 初始化结束");
            super.needlessClassMap.put(this.getClass().getName(), m);
            super.needlessUrlMap.put("/thirdApp.do", m);
        } else {
            logger.info("初始化 ThirdAppController 免认证方法 --- 初始化出错");
            throw new BusinessException("Failed to initialize ThirdAppController NeedlessCheckLogin method");
        }
    }


    /**
     * 蓝信PC穿透多个浏览器被迫下线问题处理
     * -wangqiaoming
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView distribution(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("外部系统穿透A8打开待办或已办列表------开始------------------------");
        ModelAndView mv = new ModelAndView("thirdparty/thirdpartyAccess");
        Locale locale = LocaleContext.make4Frontpage(request);
        HttpSession session = request.getSession();
        Long loginTime = System.currentTimeMillis();
        String enc = null;
        if (request.getParameter("enc") != null) {
            enc = LightWeightEncoder.decodeString(request.getParameter("enc").replaceAll(" ", "+"));
        }
        if (enc == null) {
            log.info("外部系统穿透A8打开待办或已办列表出现非法请求");
            mv.addObject("ExceptionKey", "mail.read.alert.wuxiao");
            return mv;
        }
        log.info(String.format("外部系统穿透A8打开待办或已办列表密文{enc=%s}",enc));
        Map<String, String> encMap = new HashMap<String, String>();
        String[] split = enc.split("&");
        for (String s1 : split) {
            String[] split1 = s1.split("=");
            int i = 0;
            encMap.put(split1[i],split1[++i]);
        }
        String link = null;
        long memberId = -1;
        com.seeyon.ctp.common.constants.Constants.login_useragent_from userAgentFrom = com.seeyon.ctp.common.constants.Constants.login_useragent_from.pc;
        // method
        String m = encMap.get("M");
        if (Strings.isNotBlank(m)) {
            link =m;
            log.info("外部系统穿透A8打开待办或已办列表最终页面url="+link);
            String ticket = encMap.get("L");
            SSOTicketManager.TicketInfo ticketInfo = null;
            ticketInfo = SSOTicketBean.getTicketInfoByticketOrname(ticket);
            memberId = (ticketInfo != null) ? ticketInfo.getMemberId() : memberId;
            if (memberId == -1) {
                memberId = encMap.get("U") != null ? Long.valueOf(encMap.get("U")) : memberId;
                log.info("第三方系统打开协同页面ticket无效，采用最后的方案，获取参数中的用户id是" + memberId);
            }
        } else {
            log.info("外部系统穿透A8打开待办或已办列表出现非法请求1");
            mv.addObject("ExceptionKey", "mail.read.alert.wuxiao");
            return mv;
        }
        if (memberId == -1) {
            log.info(String.format("外部系统穿透A8打开待办或已办列表出现错误，没有这个用户{enc=%s}",enc));
            mv.addObject("ExceptionKey", "mail.read.alert.noUser");
            return mv;
        }
        boolean isNeedLogout = false;
        long time2 = 0l;

        User currentUser = (User) session.getAttribute(SESSION_CURRENT_USER);
        // 当前已经登录，但登录者不是本人
        if (currentUser != null && !currentUser.isDefaultGuest()) {
            if (currentUser.getId() != memberId) {
                log.warn(String.format("外部系统穿透A8打开待办或已办列表出现错误，当前登录人不是本人{%s,待登录用户memberId=%s}",currentUser.toString(),memberId));
                mv.addObject("ExceptionKey", "mail.read.alert.exists");
                return mv;
            }
        } else {
            V3xOrgMember member = orgManager.getMemberById(memberId);
            if (member == null || member.getIsAdmin()) {
                log.warn(String.format("外部系统穿透A8打开待办或已办列表出现错误，找不到登录人{member is null}"));
                mv.addObject("ExceptionKey", "mail.read.alert.noUser");
                return mv;
            }
            LocaleContext.setLocale(session, orgManagerDirect.getMemberLocaleById(member.getId()));
            currentUser = new User();
            currentUser.setLoginTimestamp(loginTime);
            session.setAttribute(SESSION_CURRENT_USER, currentUser);
            AppContext.putThreadContext(SESSION_CONTEXT_USERINFO_KEY, currentUser);
            AppContext.initSystemEnvironmentContext(request, response, true);
            currentUser.setSecurityKey(UUIDLong.longUUID());
            currentUser.setId(memberId);
            currentUser.setName(member.getName());
            currentUser.setLoginName(member.getLoginName());
            currentUser.setAccountId(member.getOrgAccountId());
            currentUser.setLoginAccount(member.getOrgAccountId());
            currentUser.setDepartmentId(member.getOrgDepartmentId());
            currentUser.setLevelId(member.getOrgLevelId());
            currentUser.setPostId(member.getOrgPostId());
            currentUser.setInternal(member.getIsInternal());
            currentUser.setUserAgentFrom(userAgentFrom.name());
            currentUser.setSessionId(session.getId());
            currentUser.setRemoteAddr(Strings.getRemoteAddr(request));
            currentUser.setLocale(locale);
            // 判断客户端浏览器
            BrowserEnum browser = BrowserEnum.valueOf(request);
            if (browser == null) {
                browser = BrowserEnum.IE;
            }
            currentUser.setBrowser(browser);
            //添加用户拥有角色
            UserHelper.setRolesSet(orgManager.getMemberRolesForSet(currentUser.getId(), currentUser.getLoginAccount()));
            UserHelper.setResourceJsonStr(JSONUtil.toJSONString(privilegeMenuManager.getResourceCode(currentUser.getId(), currentUser.getLoginAccount())));
            CurrentUser.set(currentUser);
            isNeedLogout = true;
        }
        long time3 = System.currentTimeMillis();
        // 初始化并发必要参数
        init();
        OnlineUser onlineUser = OnlineRecorder.getOnlineUser(currentUser.getLoginName()).get(0);
        //并发数控制
        if (serverType == 2) {//server并发控制
            synchronized (isExceedMaxLoginNumberLock) {
                if (onlineUser == null) {
                    boolean isExceedMaxLoginNumber = OnlineRecorder.isExceedMaxLoginNumberServer();
                    if (isExceedMaxLoginNumber) {
                        log.info(String.format("外部系统穿透A8打开待办或已办列表出现错误{%s}", ResourceUtil.getString("mail.read.alert.ExceedMaxLoginNumber")));
                        mv.addObject("ExceptionKey", "mail.read.alert.ExceedMaxLoginNumber");
                        return mv;
                    }
                }
                onlineManager.updateOnlineState(currentUser);
            }
        }
        link =  URLDecoder.decode(link);
        link = link + (link.contains("?") ? "&" : "?") + "_isModalDialog=true";
        CTPCsrfGuard csrfGuard = CTPCsrfGuard.getInstance();
        if (csrfGuard.isEnabled()) {
            csrfGuard.updateToken(session);
            link += Functions.csrfSuffix();
        }
        mv.addObject("link", link);
        mv.addObject("isNeedLogout", isNeedLogout);
        log.info(String.format("外部系统穿透A8打开待办或已办列表---正常--------------结束----------------"));
        return mv;
    }


    /**
     * 单点登录 方法
     * @param request HTTP请求
     * @param response HTTP响应
     * @return ModelAndView 页面对象
     * @throws Exception 异常
     */
    @SuppressWarnings("deprecation")
    @NeedlessCheckLogin
    public ModelAndView access(HttpServletRequest request, HttpServletResponse response) throws Exception {

        //获取请求链接的来源
        String ua = request.getHeader("User-Agent");

        String userName = null;
        ModelAndView mav;

        String code=request.getParameter("code");
        log.info("客开，【移动单点】access获取CODE"+ code);

        Object lxUserInfoObj=request.getSession().getAttribute("lxUserInfo");
        if(lxUserInfoObj!=null)
        {
            String lxUserInfo=lxUserInfoObj.toString();
            log.info("客开，【移动单点】access缓存中的信息" + lxUserInfo);
            userName=lxUserInfo.split("-")[1];
        }
        else
        {
            if(code==null)
            {
                //蓝信认证地址
                String url= Constants.LX_AUTHORIZE_URL;
                //重定向地址
                String redirect_url= Constants.SEEYON_URL+"/seeyon/thirdApp.do?method=access&url="+request.getParameter("url");
                url=url.replace("@redirect_uri@", URLEncoder.encode(redirect_url));
                mav = new ModelAndView("plugin/thirdApp/viewMessage");
                mav.addObject("url", url);
                System.out.println("lx acc url="+url);
                log.info("客开，【移动单点】access蓝信重定向地址："+ url);
                return mav;
            }
            else
            {
                AccessToken appTokenAccess=LanxinUtil.getLxAccessToken(Constants.LX_APPID_FIRST,true);
                String appToken = appTokenAccess.getToken();
                if(appToken==null || "".equals(appToken)){return getErrorPage("单点登录错误","appToken获取不到！");}
                String userToken=LanxinUtil.getLxUserToken(appToken, code);
                if(userToken==null || "".equals(userToken)){return getErrorPage("单点登录错误","userToken获取不到！");}
                String userInfo=LanxinUtil.getLxUserInfo(appToken, userToken);
                if(userInfo==null || "".equals(userInfo)){return getErrorPage("单点登录错误","userInfo获取不到！");}
                log.info("客开，【移动单点】telNumber：" + userInfo);

                userName = LanxinUtil.getOaUser(userInfo);
                log.info("loginInfo:"+userName);

                if(userName==null || "".equals(userName)){return getErrorPage("单点登录错误","手机号：" +userInfo + "未找到对应的人员" );}
                if(userName!=null && userName!=null)
                {
                    request.getSession().setAttribute("lxUserInfo",userInfo+"-"+userName);
                }
            }
        }

    	/*if(!isMobileDevice(ua)){
    		//PC端单点
    		 log.info("客开，【PC单点】access获取Login"+ userName);
    		// String pcLoginName = URLEncoder.encode(userName, "UTF-8");
    		 //log.info("客开，【PC单点】pcLoginName获取Login"+ pcLoginName);
            String ticket = Base64Util.encode(userName + "-_-" + UUIDUtil.getAbsUUIDLong());
            String urll = Constants.SEEYON_URL+"/seeyon/login/sso?from=thridappsso&ticket="+ticket;
            log.info("客开，【pc单点】地址："+urll);
        	response.sendRedirect(urll);
    		return null;
    	}else {*/
        log.info("客开，【移动单点】access获取url"+ request.getParameter("url"));
        log.info("客开，【移动单点】access获取Login"+ userName);

        log.info("客开，【移动单点】access获取userName" + userName);

        //V3xOrgMember orgMember = orgManager.get

        // 防护：用户点击内容打开链接提示用户不存在问题
        ssoLogin(encodeUserName(userName));
        String ticketUrl= Constants.SEEYON_GETTOKEN_URL.replace("@loginName@", URLEncoder.encode(userName, "UTF-8"));

        log.info("客开，【移动单点】access获取OATOKENURL:"+ ticketUrl);
        //进行调用
        String object = httpGet(ticketUrl);
        log.info("客开，【移动单点】access获取object:"+ object);

        if(object==null){
            return getErrorPage("单点登录错误，未获取到tokenobj",object);
        }
        JSONObject tokenInfo = JSONUtil.parseJSONString(object, JSONObject.class);
        String token = tokenInfo.getString("id");

        log.info("客开，【移动单点】access获取oatoken:"+ token);
        String urltemp = LightWeightEncoder.decodeString(request.getParameter("url")) + "&token=" + token;
        mav = new ModelAndView("plugin/thirdApp/viewMessage");
        log.info("客开，【移动单点】access跳转地址：" + urltemp);
        mav.addObject("url", urltemp);
        System.out.println("jmp o000a url="+urltemp);
        return mav;
        //}

    }


    /**
     * 直接跳转
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("deprecation")
    @NeedlessCheckLogin
    public ModelAndView message(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String ticket = request.getParameter("ticket");
        String url = request.getParameter("url");
        log.info("客开，【移动消息】 获取messageUrl：" + url);
        ModelAndView mav = new ModelAndView("plugin/thirdApp/viewMessage");
        // 防护：用户点击内容打开链接提示用户不存在问题
        ssoLogin(ticket);

        String ssoUrl = Constants.SEEYON_GETTOKEN_URL.replace("@loginName@", URLEncoder.encode(decodeUserName(ticket), "UTF-8"));
        log.info("客开，【移动消息】ssoUrl: " +ssoUrl);
        //进行调用
        String object = httpGet(ssoUrl);
        log.info("客开，【移动消息】access获取tokenobj:"+ object);

        if(object==null){
            return getErrorPage("单点登录错误，未获取到tokenobj",object);
        }
        JSONObject tokenInfo = JSONUtil.parseJSONString(object, JSONObject.class);
        String token = tokenInfo.getString("id");


        String eurl = LightWeightEncoder.decodeString(url);
        String temp[] = eurl.split("html=");
        String urltemp ="";
        urltemp = temp[0] + "html=" + URLDecoder.decode(temp[1]) + "&token=" + token;
        mav.addObject("url", urltemp);
        log.info("客开，【移动消息】访问跳转地址：" + urltemp);
        return mav;
    }


    public ModelAndView getErrorPage(String errorSubject, String errorMsg) {
        ModelAndView mav = new ModelAndView("plugin/thirdApp/errorInfo");
        mav.addObject("errorSubject",errorSubject);
        mav.addObject("errorMsg", errorMsg);
        return mav;
    }


    public static String httpGet(String url) {
        // get请求返回结果
        String jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            // 发送get请求
            HttpGet request = new HttpGet(url);
            request.addHeader("Accept", "application/json");

            HttpResponse response = client.execute(request);

            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /** 读取服务器返回过来的json字符串数据 **/
                String strResult = EntityUtils.toString(response.getEntity());
                // System.out.println(strResult);
                /** 把json字符串转换成json对象 **/
//  	    jsonResult = JSONObject.fromObject(strResult);
                jsonResult = strResult;
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                // logger.error("get请求提交失败:" + url);
            }
            client.close();
        } catch (IOException e) {
            // logger.error("get请求提交失败:" + url, e);
        }

        return jsonResult;
    }

    /**
     * 单点登录
     */
    public static String ssoLogin(String ticket) {
        HttpClientUtil h = new HttpClientUtil(10 * 1000);
        String result = "failure";
        try {
            h.open(Constants.SEEYON_SSO_URL.replace("@ticket@", ticket), "get");
            h.send();
            Map<String, String> headers = h.getResponseHeader();
            Set<String> keys = headers.keySet();
            for(String key : keys) {
                if("SSOOK".equalsIgnoreCase(key)) {
                    result = "success";
                    return result;
                }
            }
        } catch(Exception e) {
            log.info("单点登录异常！,ticket:" + ticket);
            result = "exception";
        } finally {
            h.close();
        }
        return result;
    }

    /**
     * 根据用户名获取ticket
     */
    public static String encodeUserName(String userName) {
        byte[] bytes = new byte[0];
        try {
            bytes = userName.getBytes("GBK");
        } catch(UnsupportedEncodingException e) {
            log.error("", e);
        }
        byte[] baseBytes = Base64.encodeBase64(bytes, false);
        String ticket = new String(baseBytes);
        if(ticket.contains("=")) {
            ticket = ticket.replace("=", "@");
        }
        try {
            return URLEncoder.encode(ticket, "UTF-8");
        } catch(UnsupportedEncodingException e) {
            return ticket;
        }
    }

    /**
     * 根据ticket获取用户名
     */
    public static String decodeUserName(String ticket) throws Exception {
        ticket = URLDecoder.decode(ticket, "UTF-8");
        if(ticket.contains("@")) {
            ticket = ticket.replace("@", "=");
        }
        byte[] baseBytes = Base64.decodeBase64(ticket.getBytes());
        return new String(baseBytes, "GBK");
    }

    public static void main(String[] args) {
        printH5Url();
    }
    @SuppressWarnings("deprecation")
    public static void printH5Url()
    {
        String ip="127.0.0.1";
        System.out.println("蓝信回调地址:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=cu");
        System.out.println("OA首页地址:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_ALLAPP))));
        System.out.println("协同地址:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_COLL))));
        System.out.println("公文地址:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_EDOC))));
        System.out.println("讨论地址:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_BBS))));
//        System.out.println("任务地址:");
//        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_TASK))));
//        System.out.println("享空间地址:");
//        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_SHOW))));
        System.out.println("调查地址:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_INQUIRY))));
        System.out.println("新闻地址:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_NEWS))));
        System.out.println("公告地址:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_BUL))));

        System.out.println("文档地址:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_DOC))));
//        System.out.println("业务包列表地址:");
//        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_BIZ))));

        System.out.println("会议:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_MEETING))));

        System.out.println("日程:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_CALENDAR))));

        System.out.println("表单发起:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_TEMPLETE))));

        System.out.println("代办:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_PEENDINGnew))));

        System.out.println("工作台:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_ALLAPP))));



        System.out.println("工资条:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_SALARY))));



        System.out.println("表单测试:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_TEMPLETEC))));

        System.out.println("表单正式:");
        System.out.println("http://"+ip+"/seeyon/thirdApp.do?method=access&url=" + URLEncoder.encode(LightWeightEncoder.encodeString(Constants.SEEYON_APP_INDEX.replace("@html@", Constants.SEEYON_APP_TEMPLETEZ))));


        System.out.println("----------");
        String url = "MHRmZnpwbzBJNjBkcG1tYmNwc2J1anBvMGpvZWZ5L2l1bm1AaXVubT4wdGZmenBvMEk2MHhmZGlidTBpdW5tMGJtbUJxcXQvaXVubQ%3D%3D";
        String s = LightWeightEncoder.decodeString(url);
        System.out.println(s);
    }


    /*public String getUserCodeByToken(String token)throws Exception
    {
    	String un=null;
    	String url=Constants.UPESN_URL+"/mujina-idp/api/getUserInfo";
    	JSONObject jsonObject =HttpRequestUtil.sendGetUser(url,token);
    	if("E0000".equals(jsonObject.getString("ret")))
    	{
    		un=jsonObject.getJSONObject("result").getString("userName");
    	}else
    	{
    		throw new Exception(jsonObject.toString());

    	}
    	return un;
    }*/

    public static boolean isMobileDevice(String requestHeader){
        /**
         * android : 所有android设备
         * mac os : iphone ipad
         * windows phone:Nokia等windows系统的手机
         */
        String[] deviceArray = new String[]{"android","iphone","windows phone","ipad"};
        if(requestHeader == null)
            return false;
        requestHeader = requestHeader.toLowerCase();
        for(int i=0;i<deviceArray.length;i++){
            if(requestHeader.indexOf(deviceArray[i])>0){
                return true;
            }
        }
        return false;
    }

    /*public static boolean isMobile(String requestHeader) {
	      List<String> mobileAgents = Arrays.asList("ipad", "iphone os", "rv:1.2.3.4", "ucweb", "android", "windows ce", "windows mobile");
//	      String ua = request.getHeader("User-Agent").toLowerCase();
	      for (String sua : mobileAgents) {
	         if (requestHeader.indexOf(sua) > -1) {
	            return true;//手机端
	         }
	      }
	      return false;//PC端
	 }*/



    public static String getId(String url){
        //协同
        if (url.contains("collaboration")) {
            String oneUrl = url.substring(url.indexOf("?affairId=")+10);
            String id = oneUrl.substring(0, oneUrl.indexOf("&openFrom=listPending"));
            return id;
        }
        //公文
        if (url.contains("edocSummary")) {
            String oneUrl = url.substring(url.indexOf("?affairId=")+10);
            String id = oneUrl.substring(0, oneUrl.indexOf("&openFrom=listPending"));
            return id;
        }

        //调查
        if (url.contains("inquiryView")) {
            String oneUrl = url.substring(url.indexOf("?inquiryId=")+11);
            String id = oneUrl.substring(0, oneUrl.indexOf("&comeFrom=0"));
            return id;
        }
        //会议
        if (url.contains("meetingDetail")) {
            String oneUrl = url.substring(url.indexOf("?meetingId=")+11);
            String id = oneUrl.substring(0, oneUrl.indexOf("&openFrom=pending"));
            return id;
        }
        //讨论
        if (url.contains("bbsId")) {
            String oneUrl = url.substring(url.indexOf("?bbsId=")+7);
            String id = oneUrl.substring(0, oneUrl.indexOf("&from=message"));
            return id;
        }

        //公告
        if (url.contains("bulId")) {
            String oneUrl = url.substring(url.indexOf("?bulId=")+7);
            String id = oneUrl.substring(0, oneUrl.indexOf("&comeFrom=0"));
            return id;
        }

        //新闻
        if (url.contains("newsId")) {
            String oneUrl = url.substring(url.indexOf("?newsId=")+8);
            String id = oneUrl.substring(0, oneUrl.indexOf("&comeFrom=0"));
            return id;
        }

        return null;
    }



    public static String HttpsTest() {
        HttpClientUtil h = new HttpClientUtil(10 * 1000);
        String result = "failure";
        try {
            h.open("https://www.baidu.com", "get");
            h.send();
            Map<String, String> headers = h.getResponseHeader();
            Set<String> keys = headers.keySet();
            for(String key : keys) {
                if("SSOOK".equalsIgnoreCase(key)) {
                    result = "success";
                    return result;
                }
            }
        } catch(Exception e) {
            result = "exception";
        } finally {
            h.close();
        }
        return result;
    }

}
